<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SignalR连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        .success {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }

        .error {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }

        .info {
            background-color: #d1ecf1;
            border-color: #bee5eb;
            color: #0c5460;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background-color: #0056b3;
        }

        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }

        pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
        }

        .status {
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }

        .connected {
            background-color: #d4edda;
            color: #155724;
        }

        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>

<body>
    <h1>SignalR连接测试</h1>

    <div class="test-section">
        <h2>连接状态</h2>
        <div id="connectionStatus" class="status disconnected">未连接</div>
        <button onclick="testConnection()">测试连接</button>
        <button onclick="disconnect()">断开连接</button>
    </div>

    <div class="test-section">
        <h2>测试加入房间</h2>
        <div>
            <label for="roomCode">房间码:</label>
            <input type="text" id="roomCode" value="WMNNZL" maxlength="6">
        </div>
        <div>
            <label for="playerName">玩家昵称:</label>
            <input type="text" id="playerName" value="测试玩家" maxlength="15">
        </div>
        <button onclick="testJoinRoom()">测试加入房间</button>
        <div id="joinRoomResult"></div>
    </div>

    <div class="test-section">
        <h2>测试准备状态</h2>
        <button onclick="testSetReady(true)">设置准备</button>
        <button onclick="testSetReady(false)">取消准备</button>
        <div id="readyResult"></div>
    </div>

    <div class="test-section">
        <h2>连接日志</h2>
        <div id="log"
            style="height: 300px; overflow-y: auto; background-color: #f8f9fa; padding: 10px; border-radius: 5px;">
        </div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@latest/dist/browser/signalr.min.js"></script>
    <script>
        let connection = null;
        let currentRoomCode = null;
        let currentPlayerId = null;

        function log(message) {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            logDiv.innerHTML += `[${timestamp}] ${message}<br>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        function updateConnectionStatus(isConnected) {
            const statusDiv = document.getElementById('connectionStatus');
            if (isConnected) {
                statusDiv.className = 'status connected';
                statusDiv.textContent = '已连接';
            } else {
                statusDiv.className = 'status disconnected';
                statusDiv.textContent = '未连接';
            }
        }

        async function testConnection() {
            try {
                log('开始测试SignalR连接...');

                // 创建连接
                connection = new signalR.HubConnectionBuilder()
                    .withUrl('http://localhost:5152/gamehub')
                    .withAutomaticReconnect()
                    .build();

                // 设置事件处理器
                connection.on('PlayerJoined', (player) => {
                    log(`收到玩家加入事件: ${JSON.stringify(player)}`);
                });

                connection.on('PlayerLeft', (playerId) => {
                    log(`收到玩家离开事件: ${playerId}`);
                });

                connection.on('PlayerReady', (playerId, isReady) => {
                    log(`收到玩家准备状态变更: ${playerId} -> ${isReady}`);
                });

                connection.on('GameJoined', (game) => {
                    log(`收到游戏加入事件: ${JSON.stringify(game)}`);
                });

                connection.on('Error', (message) => {
                    log(`收到错误: ${message}`);
                });

                // 启动连接
                await connection.start();
                log('SignalR连接成功！');
                updateConnectionStatus(true);

            } catch (error) {
                log(`SignalR连接失败: ${error.message}`);
                updateConnectionStatus(false);
                console.error('连接错误:', error);
            }
        }

        async function disconnect() {
            if (connection) {
                try {
                    await connection.stop();
                    log('SignalR连接已断开');
                    updateConnectionStatus(false);
                } catch (error) {
                    log(`断开连接失败: ${error.message}`);
                }
            }
        }

        async function testJoinRoom() {
            if (!connection) {
                log('请先建立SignalR连接');
                return;
            }

            try {
                const roomCode = document.getElementById('roomCode').value;
                const playerName = document.getElementById('playerName').value;

                if (!roomCode || !playerName) {
                    log('请填写房间码和玩家昵称');
                    return;
                }

                log(`尝试加入房间: ${roomCode}, 玩家: ${playerName}`);

                currentRoomCode = roomCode;

                // 调用JoinGame方法 - 后端只需要房间码和玩家昵称
                await connection.invoke('JoinGame', roomCode, playerName);

                log('加入房间请求已发送');

            } catch (error) {
                log(`加入房间失败: ${error.message}`);
                console.error('加入房间错误:', error);
            }
        }

        async function testSetReady(isReady) {
            if (!connection || !currentRoomCode) {
                log('请先加入房间');
                return;
            }

            try {
                const playerName = document.getElementById('playerName').value;
                log(`设置准备状态: ${isReady}, 玩家: ${playerName}`);

                await connection.invoke('SetReady', currentRoomCode, playerName, isReady);

                log(`准备状态设置成功: ${isReady}`);

            } catch (error) {
                log(`设置准备状态失败: ${error.message}`);
                console.error('设置准备状态错误:', error);
            }
        }

        // 页面加载时自动测试连接
        window.onload = function () {
            log('页面加载完成，准备测试SignalR连接...');
        };
    </script>
</body>

</html>